<script setup lang="tsx">
import { nextTick, onMounted, onUnmounted, reactive, ref } from 'vue';
import { UUID } from 'uuidjs';
import {
  getLastouterRightTableDataList,
  getLeftTableDataLists,
  getRightTableDataLists
} from '@/service/api/modules/trace/batch-read-code-info';
import SearchBox from './modules/search.vue';

const leftPage = ref({
  pageNum: 1,
  pageSize: 200
});

const searchParams = ref<any>({
  lotId: null,
  woId: null,
  productName: null
});

const pagination = reactive({
  current: leftPage.value.pageNum,
  pageSize: leftPage.value.pageSize,
  showSizeChanger: true,
  pageSizeOptions: ['50', '100', '200', '300', '500'],
  showQuickJumper: true,
  showTotal: (total, range) => {
    console.log('object :>> ', range);

    return `共${total}条`;
  },
  total: 0,
  onChange: async (current: number, size: number) => {
    pagination.current = current;
    pagination.pageSize = size;
    leftPage.value.pageNum = current;
    leftPage.value.pageSize = size;
    getLeftTableData();
  }
});

const leftAlignId = ref<unknown>(null);

const leftTableData = ref([]);

const columnChecks = ref([
  {
    key: 'index',
    dataIndex: 'index',
    title: '序号',
    width: 70,
    align: 'center',
    checked: true
  },
  {
    key: 'lotId',
    dataIndex: 'lotId',
    title: '生产批号',
    width: 130,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'productName',
    dataIndex: 'productName',
    title: '产品型号',
    width: 140,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'printedCodeState',
    dataIndex: 'printedCodeState',
    title: '打码状态',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'qty',
    dataIndex: 'qty',
    title: '批次数量',
    width: 90,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'printCount',
    dataIndex: 'printCount',
    title: '打码数量',
    width: 90,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'customerCode',
    dataIndex: 'customerCode',
    title: '客户代码',
    width: 100,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'customerName',
    dataIndex: 'customerName',
    title: '客户名称',
    width: 250,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'createTime',
    dataIndex: 'createTime',
    title: '下发时间',
    width: 180,
    align: 'center',
    checked: true,
    ellipsis: true
  }
]);
// 右边新增
const codereading = ref([
  {
    key: 'index',
    dataIndex: 'index',
    title: '序号',
    width: 70,
    align: 'center',
    checked: true
  },
  {
    key: 'pnlId',
    dataIndex: 'pnlId',
    title: 'PNL码',
    width: 150,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'trackType',
    dataIndex: 'trackType',
    title: '动作类型',
    width: 100,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      const obj = {
        TRACKIN: '上机',
        TRACKOUT: '下机'
      };
      return obj[record.trackType] || '';
    }
  },
  {
    key: 'sliceType',
    dataIndex: 'sliceType',
    title: '片型',
    width: 70,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'dateTime',
    dataIndex: 'dateTime',
    title: '读码时间',
    width: 150,
    align: 'center',
    checked: true,
    ellipsis: true
  }
]);

const leftTableLoading = ref(false);
const currentLeftId = ref(null);
const currentMainEqpId = ref(null);
const currentLotIt = ref(null);
function getLeftTableData() {
  const params: any = { ...searchParams.value, ...leftPage.value };

  leftTableLoading.value = true;
  getLeftTableDataLists(params)
    .then(({ data, error }) => {
      if (!error) {
        data.list.forEach((item, index) => {
          item.index = index + 1;
          item.uid = UUID.genV4().hexNoDelim;
        });
        pagination.total = data.total;
        leftTableData.value = data.list;

        currentLeftId.value = data.list[0].uid;
        leftAlignId.value = data.list[0].lotId;
        getRightTableData();
      }
    })
    .finally(() => (leftTableLoading.value = false));
}

// getLeftTableData();无重置
// function reset() {
//   search();
// }

function search() {
  pagination.current = 1;
  leftPage.value.pageNum = 1;
  getLeftTableData();
}
getLeftTableData();

const rightTableData = ref([]);
const rightTableColumns = ref([
  {
    key: 'index',
    dataIndex: 'index',
    title: '序号',
    width: 70,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'modifiedEquipmentLineName',
    dataIndex: 'modifiedEquipmentLineName',
    title: '线体名称',
    width: 100,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'sumCode',
    dataIndex: 'sumCode',
    title: '打码数量',
    width: 80,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'readingCount',
    dataIndex: 'readingCount',
    title: '读码数量',
    width: 80,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'codeRate',
    dataIndex: 'codeRate',
    title: '读码率',
    width: 80,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'firstDate',
    dataIndex: 'firstDate',
    title: '初次读码时间',
    width: 150,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'lastDate',
    dataIndex: 'lastDate',
    title: '最后读码时间',
    width: 150,
    align: 'center',
    checked: true,
    ellipsis: true
  }
]);

const rightTableLoading = ref(false);

const customRow = record => {
  return {
    style: {
      background: record.uid === currentLeftId.value ? '#BAEAFA' : ''
    },
    class: record.uid === leftAlignId.value ? 'jl-table-row-selected' : '',
    onClick: () => {
      currentLeftId.value = record.uid;
      leftAlignId.value = record.lotId;
      getRightTableData();
    }
  };
};

const LastTableLoading = ref(false);
const codereadData = ref([]);
// 中间
const lastRightId = ref(null);
// 最右边
const LastCustomRow = (record: any) => {
  return {
    style: {
      background: record.uid === lastRightId.value ? '#BAEAFA' : ''
    },
    class: record.uid === lastRightId.value ? 'jl-table-row-selected' : '',
    onClick: () => {
      lastRightId.value = record.uid;
    }
  };
};
const currentRightId = ref(null);

function getRightTableDataList() {
  const obj = {
    lotId: null,
    pageSize: '9999',
    pageNum: '1',
    equipmentId: null
  };
  obj.lotId = currentLotIt.value;
  obj.equipmentId = currentMainEqpId.value;
  LastTableLoading.value = true;
  // 最右边表格接口
  getLastouterRightTableDataList(obj)
    .then(({ data, error }) => {
      if (!error) {
        data.list.forEach((item, index) => {
          item.index = index + 1;
          item.uid = UUID.genV4().hexNoDelim;
        });
        console.log(data);
        codereadData.value = data.list;
      }
    })
    .finally(() => (LastTableLoading.value = false));
}

// 中间表格点击
const rightCustomRow = (record: any) => {
  return {
    style: {
      background: record.uid === currentRightId.value ? '#BAEAFA' : ''
    },
    onClick: () => {
      currentRightId.value = record.uid;
      currentLotIt.value = record.lotId;
      currentMainEqpId.value = record.mainEqpId;
      getRightTableDataList();
    }
  };
};

const rightPagination = reactive({
  current: 1,
  pageSize: 200,
  showSizeChanger: true,
  pageSizeOptions: ['50', '100', '200', '300', '500'],
  showQuickJumper: true,
  showTotal: (total: number, range: number[]) => {
    return `共${total}条`;
  },
  total: 0,
  onChange: async (current: number, size: number) => {
    pagination.current = current;
    pagination.pageSize = size;
    getRightTableData();
  }
});

function getRightTableData() {
  rightTableLoading.value = true;

  const params = {
    lotId: leftAlignId.value,
    pageSize: rightPagination.pageSize,
    pageNum: rightPagination.current
  };
  getRightTableDataLists(params)
    .then(({ data, error }) => {
      if (!error) {
        data.list.forEach((item: any, index: number) => {
          item.index = index + 1;
          item.uid = UUID.genV4().hexNoDelim;
        });
        rightTableData.value = data.list;
        rightPagination.total = data.total;

        // 中间表格展示最右边第一条数据
        currentRightId.value = data.list[0].uid;
        currentLotIt.value = data.list[0].lotId;
        currentMainEqpId.value = data.list[0].mainEqpId;
        getRightTableDataList();
      }
    })
    .finally(() => (rightTableLoading.value = false));
}

const searchHeight = ref(42);

window.addEventListener('resize', () => {
  nextTick(() => {
    const ele = document.querySelector('.batch-read-code-info .search-box');
    const height = ele?.clientHeight;
    searchHeight.value = height || 42;
  });
});

onUnmounted(() => {
  window.removeEventListener('resize', () => {});
});
</script>

<template>
  <div
    class="jl-main-page batch-read-code-info min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto"
  >
    <SearchBox v-model:model="searchParams" @reset="reset" @search="search" />
    <ARow :gutter="[15, 8]" wrap class="w-full" :style="{ height: `calc(100% - ${searchHeight}px)` }">
      <ACol :span="8" class="h-full" style="padding-right: 0 !important">
        <ACard
          :bordered="false"
          :body-style="{ flex: 1, overflow: 'hidden' }"
          class="table-card h-full flex-col-stretch sm:flex-1-hidden card-wrapper"
        >
          <template #extra>
            <TableColumnSetting v-model:columns="columnChecks" />
          </template>
          <STable
            ref="tableWrapperRef"
            :columns="columnChecks"
            :data-source="leftTableData"
            bordered
            size="small"
            :loading="leftTableLoading"
            row-key="uid"
            :pagination="pagination"
            :custom-row="customRow"
            :row-height="23"
            :scroll="{ x: 'auto', y: 'auto' }"
            class="h-full"
          />
        </ACard>
      </ACol>
      <!-- 中间 -->
      <ACol :span="8" class="h-full" style="padding-left: 0 !important">
        <ACard
          :bordered="false"
          :body-style="{ flex: 1, overflow: 'hidden' }"
          class="table-card h-full flex-col-stretch sm:flex-1-hidden card-wrapper"
        >
          <template #extra>
            <TableColumnSetting v-model:columns="rightTableColumns" />
          </template>
          <STable
            ref="tableWrapperRef"
            :columns="rightTableColumns"
            :data-source="rightTableData"
            bordered
            size="small"
            :loading="rightTableLoading"
            row-key="uid"
            :pagination="false"
            class="h-full"
            :row-height="23"
            :custom-row="rightCustomRow"
          />
        </ACard>
      </ACol>
      <!-- 外层右边 -->
      <ACol :span="8" class="h-full" style="padding-left: 0 !important">
        <ACard
          :bordered="false"
          :body-style="{ flex: 1, overflow: 'hidden' }"
          class="table-card h-full flex-col-stretch sm:flex-1-hidden card-wrapper"
        >
          <template #extra>
            <TableColumnSetting v-model:columns="codereading" />
          </template>
          <STable
            ref="tableWrapperRef"
            :columns="codereading"
            :data-source="codereadData"
            bordered
            size="small"
            :loading="LastTableLoading"
            :pagination="false"
            row-key="uid"
            class="h-full"
            :row-height="23"
            :custom-row="LastCustomRow"
          />
        </ACard>
      </ACol>
    </ARow>
  </div>
</template>

<style lang="scss" scoped></style>
